package com.cardmanager.pro.pojo.schedule;

import org.inferred.freebuilder.FreeBuilder;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Period;
import java.util.List;


/**
 * @author Fuchun
 * @since 1.0
 */
@FreeBuilder
public interface RepaymentSchedule extends Serializable {

    Long getUserId();

    /** 还款总额。*/
    BigDecimal getTotalAmount();

    /** 总的手续费。*/
    BigDecimal getTotalCommission();

    /** 总的交易费。*/
    BigDecimal getTotalTradingFee();

    /**
     * 预计还款周期（天）。根据用户指定的帐单日、还款日及当前日期计算得出。
     */
    Period getPeriod();

    /**
     * 实际还款周期（天）。根据最终计算得出。
     */
    Period getActualPeriod();

    /** 还款计划日程。*/
    List<ScheduleItem> getSchedules();

    class Builder extends RepaymentSchedule_Builder {

        @Override
        public Builder setTotalCommission(BigDecimal totalCommission) {
            if (totalCommission != null && totalCommission.scale() > 2) {
                totalCommission = totalCommission.setScale(2, RoundingMode.HALF_UP);
            }
            return super.setTotalCommission(totalCommission);
        }

        @Override
        public Builder setTotalTradingFee(BigDecimal totalTradingFee) {
            if (totalTradingFee != null && totalTradingFee.scale() > 2) {
                totalTradingFee = totalTradingFee.setScale(2, RoundingMode.HALF_UP);
            }
            return super.setTotalTradingFee(totalTradingFee);
        }

        @Override
        public RepaymentSchedule build() {
            BigDecimal tc = BigDecimal.ZERO, ttf = BigDecimal.ZERO;
            for (ScheduleItem schedule : getSchedules()) {
                tc = tc.add(schedule.getDayCommission());
                ttf = ttf.add(schedule.getDayTradingFee());
            }
            setTotalCommission(tc)
                    .setTotalTradingFee(ttf)
                    .setActualPeriod(Period.ofDays(getSchedules().size()));

            return super.build();
        }
    }
}
